package
{
	/**
	 * 数字工具
	 * @author billowa
	 * 
	 */	
	public class BNumber
	{
		/**
		 * 将数值限制在一个区间内
		 * 
		 * @param v	数值
		 * @param min	最大值
		 * @param max	最小值
		 * 
		 */		
		public static function limitIn(v:Number,min:Number,max:Number):Number
		{
			return Math.min(Math.max(v,min),max);
		}
		
		
		
		
		/**
		 * 去除字符串中非Number类型的字符，返回Number
		 * @param string 目标字符串
		 * @return
		 * @example <listing version="3.0">
		 var _string:String;
		 
		 _string="btn1";
		 trace(BNumber.getNumber(_string));//返回 1
		 
		 _string="1a2b3c";
		 trace(BNumber.getNumber(_string));//返回 123
		 </listing>
		 */		
		public static function getNumber(string:String):Number
		{
			var myPattern:RegExp = /\D/g;
			return Number(string.replace(myPattern, ""));
		}
		
		
		
		
		
		
		
		/**
		 * 保留小数点后几位 
		 * @param num
		 * @param nAfterDot
		 * @return 
		 * 
		 */
		public static function formatNumber(num:Number,nAfterDot:int):Number
		{
			return Number(num.toFixed(Math.min(nAfterDot ,20)));
		}
		
		
		
		
		
		
		
		
		private static const chineseMapping:Array = ["","一","二","三","四","五","六","七","八","九"];
		private static const chineseLevelMapping:Array = ["","十","百","千"]
		private static const chineseLevel2Mapping:Array = ["","万","亿","兆"]
		
		/**
		 * 转换为汉字数字
		 * @private
		 */
		public static function toChineseNumber(n:int):String
		{
			var result:String = "";
			var level:int = 0;
			while (n > 0)
			{
				var v:int = n % 10;
				if (level % 4 ==0)
					result = chineseLevel2Mapping[level / 4] + result;
				
				if (v > 0)
				{
					if (level % 4 == 1 && v == 1){
						result = chineseLevelMapping[level % 4] + result;
					}else{
						result = chineseMapping[v] + chineseLevelMapping[level % 4] + result;
					}
				}
				else
				{
					result = chineseMapping[v] + result;
				}
				n = n / 10;
				level++;
			}
			
			return result;
		}
		
		
		
		private static const punctuationMapping:Array = [[",",".",":",";","?","\\","\/","[","]","`"],
			["，","。","：","；","？","、","、","【","】","·"]]
		
			
		/**
		 * @private 
		 * @param v
		 * @param m1
		 * @param m2
		 * @return 
		 * 
		 */		
		public static function toChinesePunctuation(v:String,m1:Boolean = false,m2:Boolean = false):String
		{
			var result:String = "";
			for (var i:int = 0;i<v.length;i++)
			{
				var ch:String = v.charAt(i);
				if (ch == "'")
				{
					m1 = !m1;
					result += m1?"‘":"’";
				}
				else if (ch == "\"")
				{
					m2 = !m2;
					result += m2?"“":"”";
				}
				else
				{
					var index:int = (punctuationMapping[0] as Array).indexOf(v.charAt(i));
					if (index != -1)
						result += punctuationMapping[1][index];
					else
						result += v.charAt(i);
				}
			}
			return result;
		}
	}
}